import { ElMessage, ElMessageBox } from "element-plus";
import { getCustomsDetail } from "@/api/index.js";
import {
  customs_info_category,
} from "@/utils/data.js";
/**
 * 判断url是否是http或https 
 * @param {string} path
 * @returns {Boolean}
 */
export function isHttp(url) {
  return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}

/**
 * 判断path是否为外链
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validUsername(str) {
  const valid_map = ['admin', 'editor']
  return valid_map.indexOf(str.trim()) >= 0
}

/**
 * @param {string} url
 * @returns {Boolean}
 */
export function validURL(url) {
  const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
  return reg.test(url)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validLowerCase(str) {
  const reg = /^[a-z]+$/
  return reg.test(str)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validUpperCase(str) {
  const reg = /^[A-Z]+$/
  return reg.test(str)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validAlphabets(str) {
  const reg = /^[A-Za-z]+$/
  return reg.test(str)
}

/**
 * @param {string} email
 * @returns {Boolean}
 */
export function validEmail(email) {
  const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  return reg.test(email)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function isString(str) {
  if (typeof str === 'string' || str instanceof String) {
    return true
  }
  return false
}

/**
 * @param {Array} arg
 * @returns {Boolean}
 */
export function isArray(arg) {
  if (typeof Array.isArray === 'undefined') {
    return Object.prototype.toString.call(arg) === '[object Array]'
  }
  return Array.isArray(arg)
}

export function isURL(url) {
  const pattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
  return pattern.test(url);
}

// 供应商信息校验必填
export async function submit_validate_supplier(supplier) {
  return new Promise(async (resolve, reject) => {
    if (!supplier.supplier_name) {
      ElMessage.error("请选择供应商");
      return;
    }
    if (!supplier.unit_price) {
      ElMessage.error("请输入报价(不含税单价)");
      return;
    }
    if (!supplier.purchase_days) {
      ElMessage.error("采购天数不能为空");
      return;
    }

    if (supplier.is_refund_tax == 2 && !supplier.tax_rate) {
      ElMessage.error("请输入供应商税点");
      return;
    }

    if (
      supplier.is_refund_tax == 2 &&
      (Number(supplier.tax_rate) > 13 || Number(supplier.tax_rate) == 0)
    ) {
      ElMessage.error("供应商税点必须维护>0,<=13的值");
      return;
    }

    if (supplier.is_refund_tax == 2 && Number(supplier.invoice_tax_rate) != 13) {
      ElMessage.error("发票税点必须为13");
      return;
    }
    if (
      supplier.unit_price &&
      supplier.unit_price_tax &&
      Number(supplier.unit_price) > Number(supplier.unit_price_tax)
    ) {
      ElMessage.error(" 采购含税价必须>=采购未税报价,请修改");
      return;
    }
    resolve(true);
  });
};

// 报关信息校验必填
export async function submit_validate_customs(goods_sku_customs,supplier,info) {
  return new Promise(async (resolve, reject) => {
      // 报关信息
      if (!goods_sku_customs.cn_name) {
        ElMessage.error("请输入中文报关名称");
        return;
      }
      if (!goods_sku_customs.en_name) {
        ElMessage.error("请输入英文报关名称");
        return;
      }
      if (!goods_sku_customs.cn_material) {
        ElMessage.error("请输入中文报关材质");
        return;
      }
      if (!goods_sku_customs.customs_code) {
        ElMessage.error("请输入海关编码");
        return;
      }
      if (!goods_sku_customs.declare_unit) {
        ElMessage.error("请输入报关单位");
        return;
      }
      if (!goods_sku_customs.customs_quantity) {
        ElMessage.error("请输入规格数量");
        return;
      }
      if (!goods_sku_customs.tax_rebate_rate) {
        ElMessage.error("请输入退税率");
        return;
      }

      if (
        goods_sku_customs.is_multi_platform &&
        goods_sku_customs.goods_sku_customs_info.length < 2
      ) {
        return ElMessage.error("当'是否多国家售卖'=是，则清关信息维护至少两条及以上");
      }

      const platformCountryPairs = goods_sku_customs.goods_sku_customs_info
        .filter((item) => !item.delete && (item.platform_name || item.country_id))
        .map((item) => [item.platform_name, item.country_id].join("-"));

      const hasUniquePairs =
        new Set(platformCountryPairs).size === platformCountryPairs.length;

      if (!hasUniquePairs) {
        ElMessage.error("平台和国家的组合不能相同；");
        return;
      }
      // 当前分类不需要必填
      const is_customs_info_category = customs_info_category.includes(
        info?.spu_category[0]
      );

      if (!is_customs_info_category) {
        let massageCustomsArray = [];
        goods_sku_customs.goods_sku_customs_info.forEach((item, index) => {
          if (
            !item.delete &&
            ((info?.sku_id &&
              (!item.country_id ||
                Number(item.customs_price) <= 0 ||
                !item.customs_link) &&
              !(
                item.platform_name == "amazon" &&
                (item.country_id == 262 || item.country_id == 6)
              )) ||
              (!info?.sku_id &&
                (item.platform_name || item.country_id) &&
                (!item.country_id || !item.customs_price || !item.customs_link) &&
                !(
                  item.platform_name == "amazon" &&
                  (item.country_id == 262 || item.country_id == 6)
                )))
          ) {
            massageCustomsArray.push(
              `清关信息维护第${index + 1}条：国家/报关链接不允许为空,销售价必须>0。`
            );
          }
        });
        if (massageCustomsArray && massageCustomsArray.length) {
          const messageContent = massageCustomsArray.map((d) => h('p', d));
          return ElMessageBox({
            title: "提示",
            message: h('div', {}, messageContent),
          });
        }
      }

      let massageDeclareArray = [];
      const skip_list = ["GTIN", "CAS", "其他"];
      goods_sku_customs.declare_elements_list.forEach((item, index) => {
        if (
          item.disabled &&
          item.text &&
          !skip_list.includes(item.text) &&
          (item.value === undefined || item.value === null || item.value === "")
        ) {
          massageDeclareArray.push(`申报要素维护项：第${index}项：值不能为空`);
        } else if (
          !item.disabled &&
          (!item.text ||
            item.value === undefined ||
            item.value === null ||
            item.value === "")
        ) {
          massageDeclareArray.push(`申报要素维护项：第${index}项：维护项和值不能为空`);
        }
      });

      if (massageDeclareArray && massageDeclareArray.length) {
        const messageContent = massageDeclareArray.map((d) => h('p', d));

        return ElMessageBox({
          title: "提示",
          message: h('div', {}, messageContent),
        });
      }
    if (supplier.is_refund_tax == 2) {
      const is_check = await ValidityDetection(goods_sku_customs.customs_code);
      if (is_check) {
        return ElMessage.error(
          "您所选海关编码的特殊商品标识=1，不支持退税，无法保存，请更换海关编码"
        );
      }
    }
    if (
      supplier.is_refund_tax == 2 &&
      Number(goods_sku_customs.tax_rebate_rate) == 0
    ) {
      return ElMessage.error("退税供应商的退税率必须>0，请确认");
    }

    resolve(true);
  });
};

// 海关编号合法判断
export  function ValidityDetection  (customs_goods_code) {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await getCustomsDetail({
        customs_goods_code,
      });
      if (res.data?.special_identify == 1) {
        resolve(true);
      } else {
        resolve(false);
      }
    } catch (e) {
      reject(false); // 使用 reject 传递错误
      throw Error(e);
    }
  });
};